package quick.start.ui.widget;

import quick.start.ui.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class LoadingView extends View {

    private Bitmap mImgLoading;
    private boolean isInLoading;
    private int mDegree;
    
	public LoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mDegree = 0;
        TypedArray types = context.obtainStyledAttributes(attrs, R.styleable.LoadingView);
        mImgLoading = BitmapFactory.decodeResource(getResources(), types.getResourceId(R.styleable.LoadingView_src, R.drawable.ic_launcher));
        setWillNotDraw(false);
	}
	
    public void setLoadingRes(int res) {
        mImgLoading = BitmapFactory.decodeResource(getResources(), res);
    }
	
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint p = new Paint();
        Matrix matrix = new Matrix();
        matrix.preRotate(mDegree, mImgLoading.getWidth() >> 1, mImgLoading.getHeight() >> 1);
        canvas.drawBitmap(mImgLoading, matrix, p);

        if (!isInLoading) {
            isInLoading = true;
            postDelayed(refresh, 50);
        }
    }

    private Runnable refresh = new Runnable() {
        @Override
        public void run() {
            mDegree += 45;
            if (mDegree == 360) {
                mDegree = 0;
            }
            invalidate();
            if (getVisibility() == View.VISIBLE && isShown()) {
                postDelayed(this, 50);
            } else {
                isInLoading = false;
            }
        }
    };
}
